package myplug.popup.actions;

import java.io.IOException;

import org.eclipse.core.resources.IResource;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.part.FileEditorInput;

public class GetPath implements IObjectActionDelegate
{
    private IStructuredSelection select;
    private String path;

    public GetPath()
    {
        super();
    }

    public void setActivePart(IAction action, IWorkbenchPart targetPart)
    {
    }

    public void run(IAction action)
    {
        Object obj = select.getFirstElement();
        try
        {
            IResource file = (IResource) obj;  //文件和目录
            path = file.getLocation().toOSString();
        }
        catch (ClassCastException e)
        {
            try
            {
                IJavaElement element = (IJavaElement) obj;    //包及类文件               
                path = element.getResource().getLocation().toOSString();
            }
            catch (ClassCastException e1)
            {
                try
                {
                    FileEditorInput edit = (FileEditorInput)obj; //编辑器
                    path = edit.getPath().toOSString();
                }
                catch (ClassCastException e3)
                {
                    //输出对象名（我就是利用他把上面的一个一个试出来的）
                    path = obj.getClass().toString();           
                }               
            }
        }
        try
        {
            Runtime runtime = Runtime.getRuntime();
            //调用外部命令定位文件或目录
            runtime.exec("Explorer.exe /select, " + path);
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }

   
    public void selectionChanged(IAction action, ISelection selection)
    {
        if (selection instanceof IStructuredSelection)
        {
            select = (IStructuredSelection) selection;
        }
    }
} 